/**
 *
 * jcrt and its source-code is licensed under the LGPL.
 * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
 * When copying, adapting, or redistributing this document in keeping with the guidelines above,
 * you are required to provide proper attribution to obinary.
 * If you reproduce or distribute the document without making any substantive modifications to its content,
 * please use the following attribution line:
 *
 * Copyright 2007 Atjava.com Ltd. (http://www.atjava.com) All rights reserved.
 *
 */
package com.atjava.jcrweb.manager;

import java.util.ArrayList;
import java.util.List;

import com.atjava.jcrt.BaseInfo;
import com.atjava.jcrt.JcrtSession;
import com.atjava.jcrweb.Constants;
import com.atjava.jcrweb.info.ContentInfo;
import com.atjava.jcrweb.info.DirectoryInfo;
import com.atjava.jcrweb.info.FileInfo;
import com.atjava.jcrweb.info.PrimaryKeyInfo;
import com.atjava.jcrweb.info.UserInfo;

/**
 * DataHelper
 * 
 * @author biggie
 * 
 */
public class DataHelper {

	private static final Object lockObj  = new Object();
	/**
	 * generator id
	 * 
	 * @param session
	 * @param theClass
	 * @return
	 * @throws Exception
	 */
	public static long generatorId(JcrtSession session, Class theClass)
			throws Exception {
		synchronized(lockObj){
			String key = null;
			if(theClass.equals(DirectoryInfo.class) || 
					theClass.equals(ContentInfo.class) || 
					theClass.equals(FileInfo.class)){
				key = "dcfKey";
			}else{
				key = theClass.getName();
			}
			PrimaryKeyInfo info = (PrimaryKeyInfo) session.load(PrimaryKeyInfo.class, key);
			if(info != null){
				long id = info.getId() + 1;
				info.setId(id);
				session.save(info,key);
				return id;
			}else{
				PrimaryKeyInfo newinfo = new PrimaryKeyInfo();
				newinfo.setId(1);
				newinfo.setClassName(key);
				session.save(newinfo,key);
				return 1;
			}
		}
	}
	
	public static List<BaseInfo> permissionDirpathFilter(UserInfo userInfo,List<BaseInfo> srcList)
		throws Exception{
		if(userInfo == null){
			return null;
		}
		if(Constants.ADMIN_USERNAME.equals(userInfo.getUserCode())){
			return srcList;
		}
		if(userInfo.getPermissionDirPath() == null || userInfo.getPermissionPath().length == 0){
			return null;
		}
		List<BaseInfo> list = new ArrayList<BaseInfo>();
		String[] perpath = userInfo.getPermissionPath();
		for(int i=0;i<srcList.size();i++){
			BaseInfo info = (BaseInfo)srcList.get(i);
			boolean flag = false;
			String dpath = info.getPath();
			if(!dpath.startsWith("/")){
				dpath = "/"+dpath;
			}
			for(int j=0;j<perpath.length;j++){
				String ppath = perpath[j];
				if(!ppath.startsWith("/")){
					ppath = "/"+ppath;
				}
				if(dpath.startsWith(ppath)){
					flag = true;
					break;
				}
			}
			if(flag){
				list.add(info);
			}
		}
		return list;
	}
}
